package com.changgou.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.pojo.SkuInfo;
import com.changgou.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
//添加service注解
@Service
public class SearchServiceImpl implements SearchService {
    //导入es模板类.
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    //设置每页查询条数据
    public final static  Integer PAGE_SIZE=20;

    @Override
    public Map search(Map<String, String> paramMap) throws Exception {
        //定义封装查询结果的map集合
        Map<String, Object> resultMap = new HashMap<>();

        //有条件才查询es
        if (paramMap!=null){
            //创建组合多条件查询对象
            BoolQueryBuilder boolQuery= QueryBuilders.boolQuery();

            //关键词  从参数map中 获取关键词 判断该关键词是否为空
            if (!StringUtils.isEmpty(paramMap.get("keywords"))){
                //查询条件通过must方法
                //组合查询对象，
                //如搜索条件为“小米手机”这里must会分词为“小米”和“手机”这两个词是or关系
                //加operator(Operator.AND)可以把or改为and关系
                boolQuery.must(QueryBuilders.matchQuery("name",paramMap.get("keywords")).operator(Operator.AND));
            }
            //根据品牌查询
            if (!StringUtils.isEmpty(paramMap.get("brand"))){
                //filter表示不分词查询
                //name表示查询的范围域  后面参数为查询的参数
                boolQuery.filter(QueryBuilders.termQuery("brandName",paramMap.get("brand")));
            }
            //根据规格查询 首先获取所有参数的key集合 因为规格我们指定前缀为spec_ 接着判断如果满足条件 把该值的value中的
            //%2B转化为"+"   因为规格可能有很多种  所有规格域为 specMap.key.keyword
            for (String key : paramMap.keySet()) {
                if (key.startsWith("spec_")){
                    String value = paramMap.get(key).replace("%2B", "+");
                    boolQuery.filter(QueryBuilders.termQuery("specMap."+key.substring(5)+".keyword",value));
                }
            }
            //根据价格区间查询
            if (!StringUtils.isEmpty(paramMap.get("price"))){
                String[] split = paramMap.get("price").split("-");
                if (split.length==2){
                    //rangeQuery范围查询  lte小于  gte 大于
                    boolQuery.filter(QueryBuilders.rangeQuery("price").lte(split[1]));
                }
                boolQuery.filter(QueryBuilders.rangeQuery("price").gte(split[0]));
            }

            //原生搜索实现类  本机搜索查询生成器
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            //把组合查询添加到本机搜索查询生成器.
            nativeSearchQueryBuilder.withQuery(boolQuery);

            //5:高亮
            HighlightBuilder.Field field = new HighlightBuilder
                    .Field("name")
                    .preTags("<span style='color: red'>")
                    .postTags("</span>");
            nativeSearchQueryBuilder.withHighlightFields(field);
            //品牌聚合查询
            String skuBrand="skuBrand";
            //添加聚合 定义聚合查询列名  传入聚合查询域
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));

            //分类聚合查询
            String skuSpec="skuSpec";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));

            //排序  如果传入的排序域  排序参数 不为空进入排序
            if (!StringUtils.isEmpty(paramMap.get("sortField"))&&!StringUtils.isEmpty(paramMap.get("sortRule"))){
                //如果排序参数为asc 为升序  desc为降序  (sort)排序
                if ("ASC".equals(paramMap.get("sortRule"))){
                    //传入排序的域  以及排序的参数
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(paramMap.get("sortField")).order(SortOrder.ASC));
                }else {
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(paramMap.get("sortField")).order(SortOrder.DESC));
                }
            }
        //分页参数  pageNum 当前页面
            String pageNum = paramMap.get("pageNum");
            if (pageNum==null){
                pageNum="1";
            }
            //每页显示的条数
            String pageSize = paramMap.get("pageSize");
            if (pageSize==null){
                pageSize="30";
            }
            //分页   这里注意当前页面后端从0开始  所以传入参数-1
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum)-1,Integer.parseInt(pageSize)));

            //执行查询,返回结果对象
            //三个参数分别为 本机搜索查询生成器, 对应索引库  搜索结果映射器
            AggregatedPage<SkuInfo> aggregatedPage = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    List<T> list = new ArrayList<>();
                    //通过响应获取所有的对应的信息
                    SearchHits hits = searchResponse.getHits();
                    //如果不为空 遍历响应结果
                    if (hits != null) {
                        for (SearchHit hit : hits) {
                            //把查询结果通过Json转换为对应的 索引类
                            SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
                            //替换高亮域
                            Map<String, HighlightField> highlightFields = hit.getHighlightFields();

                            if (null != highlightFields && highlightFields.size() > 0) {
                                skuInfo.setName(highlightFields.get("name").getFragments()[0].toString());
                            }
                            list.add((T) skuInfo);
                        }
                    }
                    //返回 查询结果 分页参数  查询结果总数  聚合查询结果.
                    return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());

                }
            });
            //总条数
            resultMap.put("total",aggregatedPage.getTotalElements());
            //总页数
            resultMap.put("totalPages",aggregatedPage.getTotalPages());
            //查询结果集合
            resultMap.put("rows",aggregatedPage.getContent());
            //获取品牌聚合结果
            StringTerms brandTerams= (StringTerms) aggregatedPage.getAggregation(skuBrand);
            //通过stream流把聚合结果转换为 list集合
            List<String> list = brandTerams.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("brandList",list);

            //获取规格聚合结果
            StringTerms specTerams= (StringTerms) aggregatedPage.getAggregation(skuSpec);
            List<String> list1 = specTerams.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("specList",formartSpec(list1));

            // 返回当前页
            resultMap.put("pageNum", pageNum);
            return resultMap;
        }
        return null;
    }

    public Map<String,Set<String>> formartSpec(List<String> specList){
        Map<String,Set<String>> resultMap= new HashMap<>();
        if (specList!=null&&specList.size()>0){
            for (String spec : specList) {
                //"{'颜色': '黑色', '尺码': '250度'}"
                Map<String,String> map = JSON.parseObject(spec, Map.class);
                for (String s : map.keySet()) {
                    Set<String> specSet=resultMap.get(s);
                    if (specSet==null){
                        specSet=new HashSet<String>();
                    }
                    //将规格信息存入set
                    specSet.add(map.get(s));
                    //将set存入map
                    resultMap.put(s,specSet);
                }
            }
        }
        return resultMap;
    }
}
